/**
 * @class   wosh::xtended::Scheduler
 * @brief   
 *
 *
 *
 ****************************************************************************
 * @version 0.8.161 $Id: Scheduler.h 2891 2010-08-12 01:58:59Z alex $
 * @author  Alessandro Polo
 ****************************************************************************/
/* Copyright (c) 2007-2010, WOSH - Wide Open Smart Home 
 * by Alessandro Polo - OpenSmartHome.com
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *     * Redistributions of source code must retain the above copyright
 *       notice, this list of conditions and the following disclaimer.
 *     * Redistributions in binary form must reproduce the above copyright
 *       notice, this list of conditions and the following disclaimer in the
 *       documentation and/or other materials provided with the distribution.
 *     * Neither the name of the OpenSmartHome.com WOSH nor the
 *       names of its contributors may be used to endorse or promote products
 *       derived from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY Alessandro Polo ''AS IS'' AND ANY
 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL Alessandro Polo BE LIABLE FOR ANY
 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 ****************************************************************************/

#ifndef __WOSH_Xtended_Scheduler_H__
 #define __WOSH_Xtended_Scheduler_H__

 #include <core/Thread.h>
 #include <core/ThreadMethod.h>
 #include <core/ThreadPool.h>
 #include <core/Serialization.h>
 #include <core/LogContext.h>
 #include <queue>


namespace wosh {
 template <class T> class DataFieldCollector;
 namespace xtended {


class SchedulerTask : public virtual ISerializable
 {
	WOSH_SERIALIZABLE(wosh::xtended::SchedulerTask)
	WOSH_COMPAREX_RTTI(wosh::xtended::SchedulerTask)

	public:
		/**
		 * @brief  Empty constructor.
		 */
		SchedulerTask( int64 time = 0 )
			: id(0), timeTick(time), priority(0) { }
		/**
		 * @brief  Copy constructor.
		 * @param m [in] the source object to be copied
		 */
		SchedulerTask( const SchedulerTask& m ) {
			*this = m;
		 }
		/**
		 * @brief  Empty destructor.
		 */
		virtual ~SchedulerTask() { }

/** @name Getters
 * @{
 ******************************************************************************/
	public:
		inline int64 getID() const				{ return this->id; }
		inline int64 getTimeTick() const		{ return this->timeTick; }
		inline long getPriority() const			{ return this->priority; }

		static DataFieldCollector<SchedulerTask>* getDataFields();
//@}
/** @name Setters
 * @{
 ******************************************************************************/
	public:
		inline void setID( int64 value )		{ this->id = value; }
		inline void setTimeTick( int64 value )	{ this->timeTick = value; }
		inline void setPriority( long value )	{ this->priority = value; }

//@}
/** @name Operators Overloading
 * @{
 ******************************************************************************/
	public:
		virtual SchedulerTask& operator=(const SchedulerTask& m) {
			if (this == &m) return *this; // same object?
			this->id = m.id;
			this->timeTick = m.timeTick;
			this->priority = m.priority;
			return *this;
		 }
		virtual bool operator==(const SchedulerTask &other) const {
			if ( this->id != other.id ) return false;
			if ( this->timeTick != other.timeTick ) return false;
			if ( this->priority != other.priority ) return false;
			return true;
		 }
		bool operator!=(const SchedulerTask &other) const	{ return !(*this == other);  }
		virtual bool operator<(const SchedulerTask &other) const {
			if ( this->timeTick < other.timeTick ) return true;
			if ( this->timeTick > other.timeTick ) return false;
			return this->priority > other.priority;
		 }
		virtual bool operator>(const SchedulerTask &other) const {
			if ( this->timeTick > other.timeTick ) return true;
			if ( this->timeTick < other.timeTick ) return false;
			return this->priority < other.priority;
		 }
//@}
/** @name Serialization interface
 * @{
 ******************************************************************************/
	public:
		virtual std::string toString() const;
		virtual bool updateHash( DataHashContext* hash_context ) const;
//@}
	public:
		int64 id;
		int64 timeTick;
		long priority;

};

class Scheduler;

class SchedulerTaskExecuter : public ThreadMethod
 {
	public:
		SchedulerTaskExecuter( Scheduler* parent_ptr )
			: ThreadMethod(NULL, "SchedulerTaskExecuter"), parent(parent_ptr), task(NULL) { }

		virtual ~SchedulerTaskExecuter() { }

	public:
		void setTask( SchedulerTask* task_ptr );
		void crashDetected( double probability );

	public:
		virtual void work();

	protected:
		Scheduler* parent;				///< my parent coordinator
		SchedulerTask* task;

};


#define _Scheduler_VERSION		0.12

class ISchedulerListener;
 
class Scheduler :	private wosh::ThreadImpl,
					public virtual wosh::IReflection
 {
	WOSH_CLASSNAME(wosh::xtended::Scheduler)
	WOSH_CLASS_ABSTRACT(false)

	typedef ListT<SchedulerTask*> tSchedulerTaskList;
	

	public:
		/**
		 * @brief   Default constructor. Init vars.
		 */
		Scheduler();
		/**
		 * @brief  Empty destructor.
		 */
		virtual ~Scheduler();


	public:
		WRESULT startScheduler( unsigned long synch_timeout = LIMIT_ULONG_MAX );
		WRESULT stopScheduler( unsigned long synch_timeout = LIMIT_ULONG_MAX );

		WRESULT setListener( ISchedulerListener* listener );

		WRESULT setThreadPoolCount( int worker_threads );

		WRESULT scheduleTask( SchedulerTask* newTask );
		WRESULT setupTask( int64 uid, int64 next_interrupt );

/** @name Getters
 * @{
 ******************************************************************************/
	public:
		bool isDisabled() const;

		int64 currentCronTime() const;

//@}
/** @name Setters
 * @{
 ******************************************************************************/
	public:
		void setDisabled( bool disabled = true );


		using Thread::setOwnerObject;

//@}
/** @name Internal methods
 * @{
 ******************************************************************************/
	protected:
		virtual bool initializingThread();
		virtual void runThread();
		virtual void exitingThread();
//@}

	protected:
		void task_executing( SchedulerTask* task, SchedulerTaskExecuter* executer );
		friend class SchedulerTaskExecuter;

	protected:
		bool disabled;
		MutexRW configMux;
		mutable LogContext Log;					///< my logger

		tSchedulerTaskList tasks;	///< task' queue

		ThreadPool<SchedulerTaskExecuter>* workersPool;			///< collection of worker processes

		ISchedulerListener* listener;



}; // class def




class ISchedulerListener {
	public:
		virtual void taskEvent( SchedulerTask* task, int64 time, Scheduler* source ) = 0;

	public:
		virtual ~ISchedulerListener() { }

}; // class def




 }; // namespace xtended
}; // namespace wosh

#endif //__WOSH_Xtended_Scheduler_H__
